// import 'package:flutter/material.dart';
// import 'package:qq/register_page.dart';
// import 'home_page.dart';
//
//
// void main() {
//   runApp(const MyApp());
// }
//
// // 主应用程序
// class MyApp extends StatelessWidget {
//   const MyApp({super.key});
//
//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp(
//       debugShowCheckedModeBanner: false,  // 关闭debug标志
//       title: 'QQ',
//       home: Scaffold(
//         appBar: AppBar(
//           title: const Text('登录QQ'),
//           centerTitle: true,
//           backgroundColor: Colors.blue,
//         ),
//         body: const QQLoginScreen(),
//       ),
//       theme: ThemeData(
//         primarySwatch: Colors.blue,
//         scaffoldBackgroundColor: Colors.grey[200],
//       ),
//     );
//   }
// }
//
// class QQLoginScreen extends StatefulWidget {
//   const QQLoginScreen({super.key});
//
//   @override
//   _QQLoginScreenState createState() => _QQLoginScreenState();
// }
//
// class _QQLoginScreenState extends State<QQLoginScreen> {
//   final TextEditingController _qqController = TextEditingController();
//   final TextEditingController _passwordController = TextEditingController();
//   bool _obscureText = true;
//   bool _isAgreementChecked = false;
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       body: Center(
//         child: SingleChildScrollView(
//           padding: const EdgeInsets.symmetric(horizontal: 32.0),
//           child: Column(
//             mainAxisAlignment: MainAxisAlignment.center,
//             children: [
//               const Image(image: AssetImage("images/qq.png"), width: 200),
//               const SizedBox(height: 20),
//
//               TextField(
//                 controller: _qqController,
//                 decoration: InputDecoration(
//                   hintText: '输入QQ号',
//                   filled: true,
//                   fillColor: Colors.white,
//                   border: OutlineInputBorder(
//                     borderRadius: BorderRadius.circular(10),
//                     borderSide: BorderSide.none,
//                   ),
//                 ),
//                 keyboardType: TextInputType.number,
//               ),
//               const SizedBox(height: 15),
//
//               TextField(
//                 controller: _passwordController,
//                 decoration: InputDecoration(
//                   hintText: '输入QQ密码',
//                   filled: true,
//                   fillColor: Colors.white,
//                   border: OutlineInputBorder(
//                     borderRadius: BorderRadius.circular(10),
//                     borderSide: BorderSide.none,
//                   ),
//                   suffixIcon: IconButton(
//                     icon: Icon(
//                       _obscureText ? Icons.visibility : Icons.visibility_off,
//                     ),
//                     onPressed: () {
//                       setState(() {
//                         _obscureText = !_obscureText;
//                       });
//                     },
//                   ),
//                 ),
//                 obscureText: _obscureText,
//               ),
//               const SizedBox(height: 20),
//
//               ElevatedButton(
//                 onPressed: () async {
//                   String qqNumber = _qqController.text;
//                   String password = _passwordController.text;
//                   if (!_isAgreementChecked) {
//                     ScaffoldMessenger.of(context).showSnackBar(
//                       const SnackBar(content: Text('请阅读并同意服务协议和隐私保护指引')),
//                     );
//                     return;
//                   }
//                   if (qqNumber.startsWith('5120') &&
//                       qqNumber.length == 10 &&
//                       RegExp(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)').hasMatch(password)) {
//                     ScaffoldMessenger.of(context).showSnackBar(
//                       const SnackBar(content: Text('登录成功')),
//                     );
//                     Navigator.push(
//                       context,
//                       MaterialPageRoute(builder: (context) => const HomePage()),
//                     );
//                   } else {
//                     if (!RegExp(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)').hasMatch(password)) {
//                       _passwordController.clear();
//                     }
//                     if (!(qqNumber.startsWith('5120') && qqNumber.length == 10)){
//                       _qqController.clear();
//                     }
//                     ScaffoldMessenger.of(context).showSnackBar(
//                       const SnackBar(content: Text('QQ号或密码错误，请重新输入')),
//                     );
//                   }
//                 },
//                 style: ElevatedButton.styleFrom(
//                   minimumSize: const Size(double.infinity, 50),
//                   shape: RoundedRectangleBorder(
//                     borderRadius: BorderRadius.circular(10),
//                   ),
//                   backgroundColor: Colors.blue,
//                 ),
//                 child: const Text(
//                   '登录',
//                   style: TextStyle(
//                     fontSize: 18,
//                     color: Colors.white,
//                   ),
//                 ),
//               ),
//               const SizedBox(height: 10),
//
//               Row(
//                 mainAxisAlignment: MainAxisAlignment.center,
//                 children: [
//                   Checkbox(
//                     value: _isAgreementChecked,
//                     onChanged: (value) {
//                       setState(() {
//                         _isAgreementChecked = value ?? false;
//                       });
//                     },
//                   ),
//                   const Text.rich(
//                     TextSpan(
//                       text: '已阅读并同意',
//                       style: TextStyle(color: Colors.black54),
//                       children: [
//                         TextSpan(
//                           text: '服务协议',
//                           style: TextStyle(color: Colors.blue),
//                         ),
//                         TextSpan(text: '和'),
//                         TextSpan(
//                           text: '隐私保护指引',
//                           style: TextStyle(color: Colors.blue),
//                         ),
//                       ],
//                     ),
//                   ),
//                 ],
//               ),
//               const SizedBox(height: 80),
//
//               Wrap(
//                 spacing: 10,
//                 alignment: WrapAlignment.center,
//                 children: [
//                   buildNavigationButton(
//                     icon: Icons.phone,
//                     label: '手机号登录',
//                     onTap: () {
//                       // 添加手机号登录逻辑或导航
//                       ScaffoldMessenger.of(context).showSnackBar(
//                         const SnackBar(content: Text('手机号登录未实现')),
//                       );
//                     },
//                   ),
//                   buildNavigationButton(
//                     icon: Icons.person,
//                     label: '其他方式登录',
//                     onTap: () {
//                       // 添加其他登录逻辑或导航
//                       ScaffoldMessenger.of(context).showSnackBar(
//                         const SnackBar(content: Text('其他方式登录未实现')),
//                       );
//                     },
//                   ),
//                   buildNavigationButton(
//                     icon: Icons.add,
//                     label: '注册',
//                     onTap: () {
//                       Navigator.push(
//                         context,
//                         MaterialPageRoute(builder: (context) => const RegisterPage()),
//                       );
//                     },
//                   ),
//                   buildNavigationButton(
//                     icon: Icons.more_horiz,
//                     label: '更多',
//                     onTap: () {
//                       // 添加更多功能逻辑或导航
//                       ScaffoldMessenger.of(context).showSnackBar(
//                         const SnackBar(content: Text('更多功能未实现')),
//                       );
//                     },
//                   ),
//                 ],
//               ),
//             ],
//           ),
//         ),
//       ),
//     );
//   }
//
//   Widget buildNavigationButton({
//     required IconData icon,
//     required String label,
//     required VoidCallback onTap,
//   }) {
//     return InkWell(
//       onTap: onTap,
//       child: Column(
//         children: [
//           Icon(icon, size: 40, color: Colors.black54),
//           const SizedBox(height: 5),
//           Text(
//             label,
//             style: const TextStyle(color: Colors.black54),
//           ),
//         ],
//       ),
//     );
//   }
// }

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'change_password_page.dart';
import 'register_page.dart';
import 'home_page.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'QQ',
      home: const QQLoginScreen(),
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: Colors.grey[200],
      ),
    );
  }
}

class QQLoginScreen extends StatefulWidget {
  const QQLoginScreen({super.key});

  @override
  _QQLoginScreenState createState() => _QQLoginScreenState();
}

class _QQLoginScreenState extends State<QQLoginScreen> {
  final TextEditingController _qqController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _obscureText = true;
  bool _isAgreementChecked = false;
  bool _isPasswordSaved = false; // 新增记住密码状态

  @override
  void initState() {
    super.initState();
    _loadSavedCredentials(); // 加载保存的账号密码

    //接收从注册页面返回的 QQ 号
    // WidgetsBinding.instance.addPostFrameCallback((_) async {
    //   final args = ModalRoute.of(context)?.settings.arguments as String?;
    //   if (args != null) {
    //     _qqController.text = args;
    //   }
    // });
  }

  Future<void> _loadSavedCredentials() async {
    final prefs = await SharedPreferences.getInstance();
    final savedQQ = prefs.getString('saved_qq') ?? '';
    final savedPassword = prefs.getString('saved_password') ?? '';
    final isPasswordSaved = prefs.getBool('is_password_saved') ?? false;

    setState(() {
      _isPasswordSaved = isPasswordSaved;
      if (_isPasswordSaved) {
        _qqController.text = savedQQ;
        _passwordController.text = savedPassword;
      } else {
        _qqController.clear();
        _passwordController.clear();
      }
    });
  }

  Future<void> _navigateToRegister() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const RegisterPage(),
      ),
    );

    if (result != null && result is Map<String, dynamic>) {
      final qq = result['qq'] as String?; // Get the QQ number
      if (qq != null) {
        setState(() {
          _qqController.text = qq; // Update the QQ number field
        });
      }

      final nickname = result['nickname'] as String?;
      final avatar = result['avatar'] as String?;
      if (nickname != null && avatar != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('欢迎 $nickname, 头像已设置!')),
        );
      }
    }
  }

  Future<void> _login() async {
    final prefs = await SharedPreferences.getInstance();
    final qqNumber = _qqController.text;
    final password = _passwordController.text;

    final storedPassword = prefs.getString('qq_$qqNumber');
    final nickname = prefs.getString('nickname_$qqNumber');
    final avatarPath = prefs.getString('avatar_$qqNumber');

    if (!_isAgreementChecked) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请阅读并同意服务协议和隐私保护指引')),
      );
      return;
    }

    if (storedPassword == password && nickname != null) {
      // 根据“记住密码”选项保存或清除信息
      if (_isPasswordSaved) {
        await prefs.setString('saved_qq', qqNumber);
        await prefs.setString('saved_password', password);
        await prefs.setBool('is_password_saved', true);
      } else {
        await prefs.remove('saved_qq');
        await prefs.remove('saved_password');
        await prefs.setBool('is_password_saved', false);
      }

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('登录成功')),
      );
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => HomePage(
            nickname: nickname,
            avatarPath: avatarPath ?? 'images/avatar.jpg',
          ),
        ),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('QQ号或密码错误，请重新输入')),
      );
      _passwordController.clear();
      _qqController.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('登录QQ'),
          centerTitle: true,
          backgroundColor: Colors.blue,
        ),
        body: CustomPaint(
          painter: GradientBackground(),
          child: Center(
            child: SingleChildScrollView(
              padding: const EdgeInsets.symmetric(horizontal: 32.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Image(image: AssetImage("images/qq.png"), width: 200),
                  const SizedBox(height: 25),
                  TextField(
                    controller: _qqController,
                    decoration: InputDecoration(
                      hintText: '输入QQ号',
                      filled: true,
                      fillColor: Colors.white,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: BorderSide.none,
                      ),
                    ),
                    keyboardType: TextInputType.number,
                  ),
                  const SizedBox(height: 15),
                  TextField(
                    controller: _passwordController,
                    decoration: InputDecoration(
                      hintText: '输入QQ密码',
                      filled: true,
                      fillColor: Colors.white,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: BorderSide.none,
                      ),
                      suffixIcon: IconButton(
                        icon: Icon(
                          _obscureText
                              ? Icons.visibility
                              : Icons.visibility_off,
                        ),
                        onPressed: () {
                          setState(() {
                            _obscureText = !_obscureText;
                          });
                        },
                      ),
                    ),
                    obscureText: _obscureText,
                  ),
                  const SizedBox(height: 5),
                  Row(
                    // 新增行布局
                    mainAxisAlignment:
                        MainAxisAlignment.spaceBetween, // 使修改密码靠右
                    children: [
                      Row(
                        // 新增行布局用于CheckBox和记住密码文字
                        children: [
                          Checkbox(
                            value: _isPasswordSaved,
                            onChanged: (bool? value) {
                              setState(() {
                                _isPasswordSaved = value ?? false;
                              });
                            },
                          ),
                          const Text('记住密码'), // 新增记住密码文字
                        ],
                      ),
                      GestureDetector(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const ChangePasswordPage(),
                            ),
                          );
                        },
                        child: const Text(
                          "修改密码",
                          style: TextStyle(
                            color: Colors.blue,
                            fontSize: 14,
                            decoration: TextDecoration.underline,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 5),
                  ElevatedButton(
                    onPressed: _login,
                    style: ElevatedButton.styleFrom(
                      minimumSize: const Size(double.infinity, 50),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                      backgroundColor: Colors.blue,
                    ),
                    child: const Text(
                      '登录',
                      style: TextStyle(fontSize: 18, color: Colors.white),
                    ),
                  ),
                  const SizedBox(height: 10),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Checkbox(
                        value: _isAgreementChecked,
                        onChanged: (value) {
                          setState(() {
                            _isAgreementChecked = value ?? false;
                          });
                        },
                      ),
                      const Text.rich(
                        TextSpan(
                          text: '已阅读并同意',
                          style: TextStyle(color: Colors.black54),
                          children: [
                            TextSpan(
                              text: '服务协议',
                              style: TextStyle(color: Colors.blue),
                            ),
                            TextSpan(text: '和'),
                            TextSpan(
                              text: '隐私保护指引',
                              style: TextStyle(color: Colors.blue),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 120),
                  Wrap(
                    spacing: 10,
                    alignment: WrapAlignment.center,
                    children: [
                      buildNavigationButton(
                        icon: Icons.phone,
                        label: '手机号登录',
                        onTap: () {
                          // 添加手机号登录逻辑或导航
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('手机号登录未实现')),
                          );
                        },
                      ),
                      buildNavigationButton(
                        icon: Icons.person,
                        label: '其他方式登录',
                        onTap: () {
                          // 添加其他登录逻辑或导航
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('其他方式登录未实现')),
                          );
                        },
                      ),
                      buildNavigationButton(
                        icon: Icons.add,
                        label: '    注册    ',
                        onTap: _navigateToRegister,
                      ),
                      buildNavigationButton(
                        icon: Icons.more_horiz,
                        label: '    更多    ',
                        onTap: () {
                          // 添加更多功能逻辑或导航
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('更多功能未实现')),
                          );
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ));
  }
}

Widget buildNavigationButton({
  required IconData icon,
  required String label,
  required VoidCallback onTap,
}) {
  return InkWell(
    onTap: onTap,
    child: Column(
      children: [
        Icon(icon, size: 20, color: Colors.black54),
        const SizedBox(height: 5),
        Text(
          label,
          style: const TextStyle(fontSize: 12, color: Colors.black54),
        ),
      ],
    ),
  );
}

class GradientBackground extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final Rect rect = Offset.zero & size;
    final Gradient gradient = LinearGradient(
      begin: Alignment.topCenter,
      end: Alignment.bottomCenter,
      colors: [
        Colors.pink.shade100,
        Colors.blue.shade100, // 顶部颜色
        Colors.white, // 底部颜色
      ],
    );

    final Paint paint = Paint()..shader = gradient.createShader(rect);

    canvas.drawRect(rect, paint);
  }

  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

// _querySQLHelper () async {
//   TableTestProvider testProvider = TableTestProvider();
//
//   // 通过getDatabasesPath()方法获取数据库位置
//   String databasesPath = await getDatabasesPath();
//   String path = join(databasesPath, 'test.db');
//   // 删除数据库
//   await deleteDatabase(path);
//   print("先删除数据库");
//   await testProvider.open(path);
//   print("重新创建数据库");
//   // 插入一条数据
//   Test test1 = Test();
//   test1.id =1;
//   test1.title = "Hello World1";
//   test1.done = false;
//   Test td = await testProvider.insert(test1);
//   print('inserted:${td.toMap ()}');
//   // 插入第二条数据
//   Test test2 = Test();
//   test2.id =2;
//   test2.title = "Hello dart!";
//   test2.done = false;
//   Test td2 = await testProvider.insert(test2);
//   print('inserted:${td2.toMap ()}');
//   // 更新第二条数据
//   test2.title = "I Love you";
//   int u = await testProvider.update(test2);
//   print('update:$u');
//   // 删除第一条数据
//   int d = await testProvider.delete(1);
//   print("delete:$d");
//   // 查询数据
//   Test dd = await testProvider.getTodo(2);
//   print('query:${dd.toMap()}');
//   // 关闭数据库
//   await testProvider.close();
// }
